﻿namespace RainbowNavBar.View
{
    /// <summary>
    /// TagManagement.xaml 的交互逻辑
    /// </summary>
    public partial class TagManagement : Window
    {

        #region 同步：列表数据

        /// <summary>
        /// 同步本地数据
        /// </summary>
        public delegate void LocalSyncData(TagData td);

        /// <summary>
        /// 事件：同步本地数据
        /// </summary>
        public static event LocalSyncData OnLocalSyncData;

        /// <summary>
        /// 事件：同步远程数据
        /// </summary>
        // public static event LocalSyncData OnRemoteSyncData;

        /// <summary>
        /// 事件：同步本地数据
        /// </summary>
        public static event LocalSyncData UpdateTagListData;

        /// <summary>
        /// 通知数据更新
        /// </summary>
        public static void SyncDataLocal(TagData tb)
        {
            OnLocalSyncData?.Invoke(tb);
        }

        /// <summary>
        /// 更新列表数据
        /// </summary>
        /// <param name="tb"></param>
        public static void TagListDataUpdate(TagData tb)
        {
            UpdateTagListData?.Invoke(tb);
        }

        /// <summary>
        /// 同步：将数据同步到列表中
        /// </summary>
        /// <param name="td"></param>
        private void TagManagement_OnLocalSyncData(TagData td)
        {
            // 追加数据项
            this.TagList.Items.Add(td);

            // 对数据项追加事件
            LoadingEventsAlone(this.TagList);
        }

        #endregion

        #region 窗体：构造数据

        /// <summary>
        /// 构造方法
        /// </summary>
        public TagManagement()
        {
            InitializeComponent();
            this.Loaded += TagManagement_Loaded;
            this.LocationChanged += SetEPopupBoxPint;
            TagManagement.OnLocalSyncData += TagManagement_OnLocalSyncData;

            // 更新标签管理窗口的列表
            UpdateTagListData += (other) =>
            {
                (ListBox, int) lb = this.nav.SelectedIndex switch
                {
                    0 => (this.TagList, 0),
                    1 => (this.UrlTagList,1),
                    2 => (this.ApplyTagList, 2),
                    _ => throw new NotImplementedException(),
                };
                // Debug.WriteLine(((TagData)listBox.SelectedItem).TagName);

                // 检查是否选中了项
                int _index = -1;
                if (lb.Item1.SelectedItem is TagData selectedItem && lb.Item2 == 0)
                {
                    // 设置选中索引
                    if (selectedItem.TagIndex <= 0)
                    {
                        _index = -1;
                    }
                    else if (selectedItem.TagIndex >= ApplicationConfig.TagListData.Count)
                    {
                        _index = ApplicationConfig.TagListData.Count - 1;
                    }
                    else
                    {
                        _index = selectedItem.TagIndex - 1;
                    }
                }
                else
                {
                    _index = -1;
                }
                // 利用切换选项卡来刷新数据
                this.nav.SelectedIndex = -1;
                this.nav.SelectedIndex = lb.Item2;

                // 切换到对应的索引
                lb.Item1.SelectedIndex = _index;
            };

            // 窗口关闭：将ApplicationTagList设置为Null
            this.Closing += (s, e) => { ApplicationTagList = null; };
        }

        /// <summary>
        /// 窗体加载完成后 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void TagManagement_Loaded(object sender, RoutedEventArgs e)
        {
            // 设置导航索引
            this.nav.SelectedIndex = 0;

            ApplicationWindow = this;
        }

        /// <summary>
        /// 装载数据
        /// </summary>
        private void LoadingData()
        {
            foreach (var item in ApplicationConfig.TagListData)
            {
                // 加载全部
                this.TagList.Items.Add(item);

                // 加载网址全部
                if (item.TagType == FunType.URL)
                {
                    this.UrlTagList.Items.Add(item);
                }

                // 加载应用标签
                if (item.TagType == FunType.APPLICATION)
                {
                    this.ApplyTagList.Items.Add(item);
                }
            }
            ShowDataNull(this.TagList.Items.Count, this.DataNullTagList);
            ShowDataNull(this.UrlTagList.Items.Count, this.DataNullUrlTagList);
            ShowDataNull(this.ApplyTagList.Items.Count, this.DataNullApplyTagList);
        }

        /// <summary>
        /// 列表数据为空，初始化飞机图
        /// </summary>
        /// <param name="results"></param>
        /// <param name="spanel"></param>
        private void ShowDataNull(int results, StackPanel spanel)
        {
            // 如果为空则显示飞机图
            if (results == 0)
            {
                spanel.Visibility = Visibility.Visible;
                return;
            }
            else
            {
                spanel.Visibility = Visibility.Collapsed;
            }
        }

        /// <summary>
        /// 消息框弹出位置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SetEPopupBoxPint(object sender, EventArgs e)
        {
            // 信息框弹出位置
            if (ApplicationTip != null && ApplicationTip.Owner == this)
            {
                ApplicationTip.Left = this.Left + ((this.Width / 2) - (ApplicationTip.Width / 2));
                ApplicationTip.Top = this.Top + 40;
            }
        }

        #endregion

        #region 事件：装载事件

        /// <summary>
        /// 装载事件
        /// </summary>
        /// <param name="lb"></param>
        private void LoadingEvents(ListBox lb)
        {
            // 装载事件
            Dispatcher.BeginInvoke(new Action(() =>
            {
                for (int i = 0; i < lb.Items.Count; i++)
                {
                    if (lb.ItemContainerGenerator.ContainerFromIndex(i) is ListBoxItem listBoxItem)
                    {
                        if (listBoxItem.Template.FindName("BtnUpdate", listBoxItem) is Button btnUpdate)
                        {
                            btnUpdate.Click += (s, e) => BtnUpdate_Click(s, e, lb);
                        }
                        if (listBoxItem.Template.FindName("BtnDele", listBoxItem) is Button btnDele)
                        {
                            btnDele.Click += (s, e) => BtnDele_Click(s, e, lb);
                        }
                        if (listBoxItem.Template.FindName("IsTagEnable", listBoxItem) is CheckBox check)
                        {
                            //btnDele.Click += (s, e) => BtnDele_Click(s, e, lb);
                            check.Checked += (s, e) => CheckBox_Cheaked(s, e, lb);
                            check.Unchecked += (s, e) => CheckBox_UnCheaked(s, e, lb);
                        }
                    }
                }
            }), System.Windows.Threading.DispatcherPriority.Loaded);
        }

        /// <summary>
        /// 装载事件(单个)
        /// </summary>
        /// <param name="lb"></param>
        private void LoadingEventsAlone(ListBox lb)
        {
            // 装载事件
            Dispatcher.BeginInvoke(new Action(() =>
            {
                if (lb.ItemContainerGenerator.ContainerFromIndex(lb.Items.Count - 1) is ListBoxItem listBoxItem)
                {
                    if (listBoxItem.Template.FindName("BtnUpdate", listBoxItem) is Button btnUpdate)
                    {
                        btnUpdate.Click += (s, e) => BtnUpdate_Click(s, e, lb);
                    }
                    if (listBoxItem.Template.FindName("BtnDele", listBoxItem) is Button btnDele)
                    {
                        btnDele.Click += (s, e) => BtnDele_Click(s, e, lb);
                    }
                    if (listBoxItem.Template.FindName("IsTagEnable", listBoxItem) is CheckBox check)
                    {
                        //btnDele.Click += (s, e) => BtnDele_Click(s, e, lb);
                        check.Checked += (s, e) => CheckBox_Cheaked(s, e, lb);
                        check.Unchecked += (s, e) => CheckBox_UnCheaked(s, e, lb);
                    }
                }
            }), System.Windows.Threading.DispatcherPriority.Loaded);
        }

        #endregion

        #region 标签：开启关闭

        /// <summary>
        /// 开启标签
        /// </summary>
        /// <param name="s"></param>
        /// <param name="e"></param>
        /// <param name="lb"></param>
        private void CheckBox_Cheaked(object s, RoutedEventArgs e, ListBox lb)
        {
            if (lb.SelectedItem is TagData selected)
            {
                // 设置状态:防多次绑定事件
                selected.IsModify = true;

                // 封装字典
                var updatedRecord = new System.Collections.Generic.Dictionary<string, string>
                {
                    //{ "TagName",selected.TagName },
                    { "TagEnable", "True" },
                    //{ "TagColor", GlobalFunction.ToHexString(selected.TagColor,sign:true) },
                };
                //ApplicationConfig.configManager.UpdateDataRecord(selected.TagName, updatedRecord);
                ApplicationConfig.TagUpdated(selected, selected.TagName, updatedRecord);

            }
        }

        /// <summary>
        /// 关闭标签
        /// </summary>
        /// <param name="s"></param>
        /// <param name="e"></param>
        /// <param name="lb"></param>
        private void CheckBox_UnCheaked(object s, RoutedEventArgs e, ListBox lb)
        {
            if (lb.SelectedItem is TagData selected)
            {
                var updatedRecord = new System.Collections.Generic.Dictionary<string, string>
                {
                    { "TagEnable", "False" }
                };
                //ApplicationConfig.configManager.UpdateDataRecord(selected.TagName, updatedRecord);
                ApplicationConfig.TagUpdated(selected, selected.TagName, updatedRecord);
            }
        }

        #endregion

        #region 事件：更新删除

        /// <summary>
        /// 删除事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnDele_Click(object sender, RoutedEventArgs e, ListBox lb)
        {
            if (lb.SelectedItem is TagData selected)
            {
                if (MessageBox.Show("标签类型：" + selected.TagType.ToString() + "\n标签名称：" + selected.TagName + "\n标签描述：" + selected.TagDescription + "\n映射地址：" + selected.TagAddress, "操作提示：确定要删除此标签数据吗?", MessageBoxButton.OKCancel, MessageBoxImage.Question) == MessageBoxResult.OK)
                {
                    // 删除数据记录
                    ApplicationConfig.TagRemove(selected);
                    // 删除列表记录
                    lb.Items.Remove(lb.SelectedItem);
                    MessBox($"删除成功：{selected.TagName}", EMColor.Info);
                }
            }
        }

        /// <summary>
        /// 更新事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnUpdate_Click(object sender, RoutedEventArgs e, ListBox lb)
        {
            if (lb.SelectedItem is TagData selected)
            {
                //MessBox("Update:" + selected.TagName, EMColor.Success);

                GlobalFunction.ShowChildWindowWithMask(this, new Add(false, selected), this.MaskLayer);
                return;
            }
        }

        #endregion

        #region 查询：标签分类

        /// <summary>
        /// 查询所有标签
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SearchTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            var results = ApplicationConfig.TagListData.Where(tag => tag.TagName != null && tag.TagName.IndexOf(this.SearchTextBox.Text, StringComparison.OrdinalIgnoreCase) >= 0 || tag.TagAddress.IndexOf(this.SearchTextBox.Text, StringComparison.OrdinalIgnoreCase) >= 0).ToList();


            // 清空列表
            this.TagList.Items.Clear();

            // 如果为空则显示飞机图
            if (results.Count == 0)
            {
                this.DataNullTagList.Visibility = Visibility.Visible;
                return;
            }
            else
            {
                this.DataNullTagList.Visibility = Visibility.Collapsed;
            }

            // 遍历查询结果
            foreach (var result in results)
            {
                this.TagList.Items.Add(result);
            }
            if (this.TagList.Items.Count > 0) { LoadingEvents(this.TagList); }
        }

        /// <summary>
        /// 查询网址标签
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SearchTextBoxUrlTags_TextChanged(object sender, TextChangedEventArgs e)
        {
            var results = ApplicationConfig.TagListData.Where(tag => tag.TagName != null && tag.TagType == FunType.URL && (tag.TagName.IndexOf(this.SearchTextBoxUrlTags.Text, StringComparison.OrdinalIgnoreCase) >= 0 || tag.TagAddress.IndexOf(this.SearchTextBoxUrlTags.Text, StringComparison.OrdinalIgnoreCase) >= 0)).ToList();

            // 清空列表
            this.UrlTagList.Items.Clear();

            // 如果为空则显示飞机图
            if (results.Count == 0)
            {
                this.DataNullUrlTagList.Visibility = Visibility.Visible;
                return;
            }
            else
            {
                this.DataNullUrlTagList.Visibility = Visibility.Collapsed;
            }

            // 遍历查询结果
            foreach (var result in results)
            {
                Debug.WriteLine(result.TagType);
                this.UrlTagList.Items.Add(result);
            }

            if (this.UrlTagList.Items.Count > 0) { LoadingEvents(this.UrlTagList); }
        }

        /// <summary>
        /// 查询应用标签
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SearchTextBoxApplyTags_TextChanged(object sender, TextChangedEventArgs e)
        {
            var results = ApplicationConfig.TagListData.Where(tag => tag.TagName != null && tag.TagType == FunType.APPLICATION && (tag.TagName.IndexOf(this.SearchTextBoxApplyTags.Text, StringComparison.OrdinalIgnoreCase) >= 0 || tag.TagAddress.IndexOf(this.SearchTextBoxApplyTags.Text, StringComparison.OrdinalIgnoreCase) >= 0)).ToList();

            // 清空列表
            this.ApplyTagList.Items.Clear();

            // 如果为空则显示飞机图
            if (results.Count == 0)
            {
                this.DataNullApplyTagList.Visibility = Visibility.Visible;
                return;
            }
            else
            {
                this.DataNullApplyTagList.Visibility = Visibility.Collapsed;
            }

            // 遍历查询结果
            foreach (var result in results)
            {
                this.ApplyTagList.Items.Add(result);
            }

            if (this.ApplyTagList.Items.Count > 0) { LoadingEvents(this.ApplyTagList); }
        }

        #endregion

        #region 管理：添加同步

        /// <summary>
        /// 添加新标签
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Add_Click(object sender, RoutedEventArgs e)
        {
            GlobalFunction.ShowChildWindowWithMask(this, new Add(true), this.MaskLayer);
        }

        /// <summary>
        /// 同步数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Sync_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("同步数据", "提示");
        }

        #endregion

        #region 选项：标签管理

        /// <summary>
        /// 标签管理器选项卡
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Nav_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // 清空列表所有数据
            this.TagList.Items.Clear();
            this.UrlTagList.Items.Clear();
            this.ApplyTagList.Items.Clear();
            // 加载数据
            LoadingData();
            // 装载事件
            int _index = 0;
            switch (this.nav.SelectedIndex)
            {
                case 0: _index = 0; if (this.TagList.Items.Count > 0) { LoadingEvents(this.TagList); } break;
                case 1: _index = 1; if (this.UrlTagList.Items.Count > 0) {  LoadingEvents(this.UrlTagList); } break;
                case 2: _index = 2; if (this.ApplyTagList.Items.Count > 0) { LoadingEvents(this.ApplyTagList); } break;
            };

            this.Tabs.SelectedIndex = _index;
        }

        #endregion




    }
}
